package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        this.socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true){
            // 1. 创建 DatagramPacket 对象，用于接收客户端的请求
            DatagramPacket requestDatagram = new DatagramPacket(new byte[4096], 4096);
            // 2. 等待接收客户端的请求
            socket.receive(requestDatagram);
            // 3. 解析客户端请求
            String request = new String(requestDatagram.getData(), 0, requestDatagram.getLength());
            // 4. 接收到客户端的请求后，根据请求计算响应
            String response = process(request);
            // 5. 根据响应，构建 DatagramPacket 用于返回响应
            DatagramPacket responseDatagram = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestDatagram.getSocketAddress());
            // 6. 返回响应
            socket.send(responseDatagram);
            System.out.printf("[%s %d] request: %s, response: %s",
                    requestDatagram.getAddress().toString(), requestDatagram.getPort(), request, response);
            System.out.println();
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
